// pages/refund/refund.js
const app = getApp();
let Api = require('../../api/api.js');
const Base = require('../../config.js');
Page({
    data: {
        tipText: '',
        showToast: false,
        status: '',
        ordernumber: '',
        orderDetail:[],
        subtotal: 0,
        subtotal_1: 0, 
        allMoney:"",
        refundType:'仅退款',
        serviceType:'', //服务类型
        content: '多拍/错拍/不想要',//退货原因
        picData:[],
        desc: '',//退款说明
        imgString: '', //退款图片(请求接口doUploadImg返回图片路径，多张图逗号隔开上传)
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options,'申请退款options')
        let self = this;
        if (options.refundType == '仅退款'){
            self.setData({
                serviceType: 2,
            })
        } else if (options.refundType == '退货退款'){
            self.setData({
                serviceType:1,
            }) 
        }
        self.setData({
            status: options.status,
            ordernumber: options.ordernumber,
            refundType: options.refundType,
        })
        Api.get(app.globalData.mallDomain, { //18）我的订单列表 
            doShowMyOrderList: 1,
            token: app.globalData.token, //  测试用options.token  线上用app.globalData.token
            status: options.status,
            ordernumber: options.ordernumber, // 订单号  查询单个订单时传入
        }).then(res => {
            console.log(res,'退款订单列表')
            let list = [];
            if (res.data.list != '') {
                res.data.list[0].list.forEach(ele => {
                    //插入数据
                    list.push({
                        WoAmount: ele.WoAmount,
                        money: ele.wsPrice,
                        wsPrice: parseInt(ele.wsPrice),
                        wsPrice_1: ele.wsPrice.substring(ele.wsPrice.length - 2, ele.wsPrice.length),
                        wpCover: ele.wpCover,
                        customvalue: ele.customvalue,
                        woInt: ele.woInt,
                        wpId: ele.wpId,
                        wpName: unescape(ele.wpName),
                        wpViceName: ele.wpViceName,
                        wsOneValue: ele.wsOneValue,
                    })
                })
            }
            for (let i = 0; i < list.length; i ++){
                self.setData({
                    subtotal: parseInt(self.data.subtotal + parseFloat(list[i].money) * parseFloat(list[i].woInt)),
                    allMoney: self.data.subtotal + parseFloat(list[i].money) * parseFloat(list[i].woInt),
                })  
            }
            self.setData({
                subtotal_1: self.data.allMoney.toString().substring(self.data.allMoney.toString().length - 2, self.data.allMoney.toString().length),
            })  
            self.setData({
                orderDetail: list
            })
        })
    },
    /**
     * 提交申请退货
     */
    submitRefund: function (e) {
        let self = this;
        console.log(self.data.picData,'退款照片路径')
        if (self.data.picData == ''){
            self.setData({
                showToast: true,
                tipText: '请上传凭证再提交申请！',
            })
            setTimeout(function () {
                self.setData({
                    showToast: false,
                    tipText: '',
                })
            }, 1000)
        } else {
            //上传图片
            var uploadImgCount = 0;
            for (let i = 0; i < self.data.picData.length; i++) {
                wx.uploadFile({
                    url: app.globalData.mallDomain + '?doUploadImg=1',
                    filePath: self.data.picData[i],
                    name: 'img',
                    success: function (ret) {
                        uploadImgCount++;
                        var data = JSON.parse(ret.data);
                        self.setData({
                            imgString: self.data.imgString + data['filename'] + ','
                        })
                        //  Base.service.base  + filename  服务器地址
                        // //服务器返回格式: {"status":"y","filename":"/WxAppImage/2018/10/12/201810120952199921.jpg"}
                        //如果是最后一张,则隐藏等待中  提交申请退款 退货数据  
                        if (uploadImgCount == self.data.picData.length) {
                            Api.get(app.globalData.mallDomain, { //19）修改订单状态
                                doChangeOrderStatus: 1,
                                token: app.globalData.token, //  测试用7324f82d-3440-4a1a-b3a7-af0885f5fb42  线上用app.globalData.token
                                status: 3,
                                ordernumber: self.data.ordernumber, // 订单号
                                type: self.data.serviceType,
                                content: self.data.content,
                                desc: self.data.desc,
                                img: self.data.imgString.replace(/\s+/g, "").substring(0, self.data.imgString.replace(/\s+/g, "").length - 1),
                            }).then(res => {
                                console.log(res, '申请退货结果')
                                if (res.data.msg == '118') {
                                    self.setData({
                                        tipText: '提交成功',
                                        showToast: true,
                                    })
                                    setTimeout(function () {
                                        let pages = getCurrentPages();
                                        let prevPage = pages[pages.length - 2];  //上一个页面
                                        let prevPage_1 = pages[pages.length - 3];  //上上一个页面
                                        for (let i = 0; i < prevPage_1.data.orderList.length; i++){ //修改我的订单页面订单状态
                                            if (self.data.ordernumber == prevPage_1.data.orderList[i].ordernumber){
                                                let up = "orderList["+ i +"].orderstatus";
                                                prevPage_1.setData({
                                                    [up]:'申请退款'
                                                })
                                                let listData = prevPage_1.data.orderList;
                                                listData.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                                                prevPage_1.setData({
                                                    orderList: listData
                                                })
                                            }
                                        }
                                        self.setData({
                                            tipText: '',
                                            showToast: false
                                        })
                                        prevPage.setData({ //修改订单详情订单状态
                                            bannerSrc: '../../images/dcl.png',
                                            orderstatus: '申请退款',
                                            status: 3,
                                        })
                                        wx.navigateBack({
                                            delta: 1
                                        })
                                    }, 1000)
                                }
                            })
                        }
                    },
                    fail: function (res) {
                        console.log(res)
                        wx.hideToast();
                        wx.showModal({
                            title: '错误提示',
                            content: '上传图片失败',
                            showCancel: false,
                        })
                    }
                });
            }
        }
        
    },
    /**
    * 上传凭证
    */
    uploadPic: function (e) {
        let self = this;
        wx.showActionSheet({
            itemList: ["从相册中选择", "拍照"],
            itemColor: "#ed1709",
            success: function (res) {
                console.log(res)
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        self.chooseWxImage("album");
                    } else if (res.tapIndex == 1) {
                        self.chooseWxImage("camera");
                    }
                }
            }
        })
    },
    chooseWxImage: function (type) {
        let self = this;
        wx.chooseImage({
            count: 3,
            sizeType: ["original", "compressed"],
            sourceType: [type],
            success: function (res) {
                if (type == 'album'){
                    self.setData({
                        picData: []
                    })
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let up = "picData[" + i + "]";
                        self.setData({
                            [up]: res.tempFilePaths[i]
                        })
                    }
                } else if (type == 'camera'){
                    let picList = self.data.picData;
                    picList.push(res.tempFilePaths[0])
                    if (picList.length < 4){
                        self.setData({
                            picData: picList
                        })  
                    }else{
                        picList.splice(0, 1);
                        self.setData({
                            picData: picList
                        }) 
                    }
                   
                }
               
            },
        })
    },
    /**
     * 预览图片
     */
    handleImagePreview(e) {
        console.log(e)
        let self = this;
        let src = e.currentTarget.dataset.src;//获取data-src
        let imgList = self.data.picData;//获取data-list
        //图片预览
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
    },
    /**
     * 删除图片
     */
    deletePic: function (e) {
        let self = this;
        let list = self.data.picData;
        list.splice(e.currentTarget.dataset.index, 1)
        self.setData({
            picData: list
        })
    },

    /**
     * 点击单选框  服务类型
     */
    radioChangeServiceType: function (e) {
        console.log(e)
        let self = this;
        if (e.detail.value == '退货退款'){
            self.setData({
                serviceType:1,
            })
        } else if (e.detail.value == '仅退款'){
            self.setData({
                serviceType: 2,
            })
        }
        
    },
    /**
     * 点击单选框  退货原因
     */
    radioChangeContent: function (e) {
        console.log(e)
        let self = this;
        self.setData({
            content: e.detail.value
        })
    },
    /**
     * 点击单选框  退货原因
     */
    refundInstructions: function (e) {
        console.log(e)
        let self = this;
        self.setData({
            desc: e.detail.value
        })
    },
    
})